const express = require('express')
const router = express.Router()
const userModel = require('../db/models/userModel')
const md5 = require('md5')
const STATUSCODE = require('../utils/constants')
const {signToken} = require('../utils/tokenUtils')
const verifyToken = require('../middlewares/verifyToken')
router.use(express.urlencoded({extended:false}))
//登录验证接口
router.post('/admin/login',async (req,res)=>{
    const {username,pwd} = req.body
    // console.log(req.body);
    const user =await userModel.findOne({username,pwd:md5(pwd)})
    // console.log(user._id.toString());
    // console.log(typeof user.username);
    
    // res.send(1)
    try {
        if(user){
            //登录成功
            res.json({
                "code":STATUSCODE.SUCCESS,
                "token":signToken({username,userId:user._id.toString()}),
                "data": {
                    user
                },
                "message": "登陆请求成功"
            })
        }else{
            //登录失败
             res.json({
                "code":STATUSCODE.DATAERROR,
                "message": "登陆失败"
            })
        }
    } catch (error) {
        res.json({
             "code":STATUSCODE.SERVERERROR,
             "message": "服务器或数据库错误"
        })
    }
})
//获取用户信息接口
router.get('/admin/info',verifyToken,async (req,res)=>{
    const userId = req.userId
    // console.log(userId);
    
    try {
        const data =await userModel.findById(userId)
        // console.log(data);
        // {
        //     _id: new ObjectId('6809b8815e985b157558a21d'),
        //     username: 'admin',
        //     pwd: '96e79218965eb72c92a549dd5a330112',
        //     profile: '/upload/admin.png',
        //     create_time: '2025-04-24 12:05:21'
        //   }
        res.json({
            "code":STATUSCODE.SUCCESS,
            data,
            "message":"获取用户信息成功"
        })
    } catch (error) {
        res.json({
            "code":STATUSCODE.SERVERERROR,
            "message":"服务器错误"
        })
    }
})
module.exports=router